//
//  DUSubMenuButton.swift
//  SimpleCal
//
//  Created by 杜晓祥 on 2021/11/3.
//

import Cocoa

class DUSubMenuButton: BaseButton {
    
    private var mouseInButton = false
    private let button_image_rect = NSMakeRect(24, 24, 60, 60)
    private let button_title_rect = NSMakeRect(5,5 , 100, 20)
    
    var btnTitle:String?
    
    init(frame frameRect: NSRect, withTitle title: String) {
        super.init(frame: frameRect)
        self.btnTitle = title
        self.title = ""
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.image = nil
        self.btnTitle = title
        self.title = ""
    }
    
    

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
    }
    
    override func mouseEntered(with event: NSEvent) {
        mouseInButton = true
        self.needsDisplay = true
    }
    
    override func mouseExited(with event: NSEvent) {
        mouseInButton = false
        self.needsDisplay = true
    }
    
    override func layout() {
//        print("-----")
//    }
//
//    override func viewDidMoveToWindow() {
        let title_layer = CATextLayer()
        title_layer.contentsScale = 2
        title_layer.string = btnTitle
        title_layer.alignmentMode = .center
        title_layer.fontSize = 14
        title_layer.foregroundColor = NSColor.black.cgColor
        title_layer.frame = button_title_rect
        
        self.layer?.addSublayer(title_layer)
        //print(btnTitle)
        self.layer?.cornerRadius = 10
        self.layer?.borderWidth = 1
        self.layer?.borderColor = NSColor.gray.cgColor
        
        addTrackingRect(self.bounds, owner: self, userData: nil, assumeInside: false)
    }
    
    override var wantsUpdateLayer: Bool {
        return true
    }
    
    override func updateLayer() {
        if mouseInButton {
            self.layer?.backgroundColor = NSColor.gray.cgColor
        } else {
            self.layer?.backgroundColor = nil//NSColor.white.cgColor
        }
    }
    
    func setFixedConstraint(width: Float, height: Float) {
        let fixedWidth = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 110)
        let fixedHeight = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 30)
        self.addConstraints([fixedWidth, fixedHeight])
    }
    
}
